package com.bookstore.servlet;

import com.bookstore.bean.User;
import com.bookstore.mappers.UserMapper;
import com.bookstore.services.Impl.UserServiceImpl;
import com.bookstore.services.UserService;
import com.bookstore.utils.DruidUtils;
import com.bookstore.utils.WebUtils;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Map;

@WebServlet(name = "UserServlet", value = "/UserServlet")
public class UserServlet extends BaseServlet {
    UserService userService=new UserServiceImpl();
    /**
     * 登录
     */
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String time = request.getParameter("time");
        User login = userService.login(new User(null,username,password,null));
        if(login!=null){
            System.out.println(login);
            HttpSession session = request.getSession();
            session.setAttribute("user",login);
            if (time.equals("记住七天！！！！")) {
                session.setMaxInactiveInterval(60*60*7);
            }
            response.sendRedirect("pages/user_success.jsp");
        }else {
            request.setAttribute("msg","密码或账号错误！！！");
            response.sendRedirect("index.jsp");
        }
    }

    /**
     * 用户注册
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, String[]> map = request.getParameterMap();
        User user = WebUtils.copyParamToBean(new User(), map);
        SqlSession sqlSession = DruidUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        if(user==null){
            request.setAttribute("msg","账号或密码不能为空！！！");
            request.getRequestDispatcher("register.jsp").forward(request,response);
        }else {
            int insertUser = mapper.insertUser(user);
            if(insertUser>0){
                response.sendRedirect(request.getContextPath()+"index.jsp");
            } else {
                request.setAttribute("msg","用户已存在！！！");
                request.getRequestDispatcher("register.jsp").forward(request,response);
            }
        }
    }
}
